/********************************************************************************
 * Copyright(c) 2020-2025 BST All rights reserved.
 * - Filename
 * - Author
 * - Version V1.0.0
 * - Date    2025/08/05
 * - Brief
 * - FunctionList:
 ******************************************************************************
 * History:
 *
 *
 *
 ******************************************************************************
 */

#include <condition_variable>
#include <csignal>
#include <fstream>
#include <iostream>
#include <mutex>

#include "ConfigSingleton.hpp"
#include "DetectInfoReciver.hpp"
#include "ImageSender.hpp"
#include "Logger.hpp"

static std::mutex mExitMutex;
static std::condition_variable mExitCond;
static bool mExit = false;

static void sigtermHandler(int sig) {
  {
    std::lock_guard<std::mutex> lock(mExitMutex);
    mExit = true;
  }
  mExitCond.notify_one();
}

static void waitForExit() {
  mExit = false;
  signal(SIGHUP, SIG_IGN);          // 连接挂断
  signal(SIGQUIT, SIG_IGN);         // 终端退出
  signal(SIGPIPE, SIG_IGN);         // 向无读进程的管道写数据
  signal(SIGTTOU, SIG_IGN);         // 后台程序尝试写操作
  signal(SIGTTIN, SIG_IGN);         // 后台程序尝试读操作
  signal(SIGTERM, sigtermHandler);  // 终止
  signal(SIGINT, sigtermHandler);   // 终端中
  std::unique_lock<std::mutex> lock(mExitMutex);
  mExitCond.wait(lock, [&] { return mExit; });
}

int main(int argc, const char* argv[]) {
  if (argc < 2) {
    LOGE("replay.json needed !!");
    return 0;
  };
  ConfigSingleton::get().loadConfig(std::string(argv[1]));

  LOGI("ReplayMode:%d, Periond:%d,ImagePath:%s,  Subip:%s",
       ConfigSingleton::get().getReplayType(),
       ConfigSingleton::get().getSendPeriod(),
       ConfigSingleton::get().getImagePath().c_str(),

       ConfigSingleton::get().getSubscribleIp().c_str());

  auto context = std::make_shared<vzmq::VzmqContext>();
  auto sender = std::make_shared<ImageSender>(context.get());
  auto reciver = std::make_shared<DetectInfoReciver>(context.get());
  sender->start(ConfigSingleton::get().getImagePath());
  reciver->start(ConfigSingleton::get().getSubscribleIp(),
                 [&](const std::shared_ptr<DetectionFrame>&& f) {});
  waitForExit();
  sender->stop();
  reciver->stop();
  return 0;
}